package cz.boxdesign.library.service;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import cz.boxdesign.library.common.dao.CommonDao;
import cz.boxdesign.library.common.dao.DatabaseOperationException;
import cz.boxdesign.library.entity.LibraryEntity;

public abstract class CommonServiceAbstract<T extends LibraryEntity> implements CommonService<T> {

  private Class<T> clazz = null;

  @Autowired
  @Qualifier(value = "commonDao")
  private CommonDao dao;

  /**
   * Parameter clazz of CommonService must be set here
   */
  @PostConstruct
  protected abstract void initService();

  @Override
  public List<T> getAll() throws DatabaseOperationException {
    validate();
    return this.dao.getDao(clazz).getAll();
  }

  @Override
  public T getById(Integer id) throws DatabaseOperationException {
    validate();
    return (T) this.dao.getDao(clazz).getById(id);
  }

  @Override
  public List<T> getByClause(String clause) throws DatabaseOperationException {
    validate();
    return this.dao.getDao(clazz).getByClause(clause);
  }

  @Override
  public void updateEntity(T entity) throws DatabaseOperationException {
    validate();
    this.dao.getDao(clazz).updateEntity(entity);
  }

  @Override
  public void insertEntity(T entity) throws DatabaseOperationException {
    validate();
    this.dao.getDao(clazz).insertEntity(entity);
  }

  @Override
  public void deleteEntity(T entity) throws DatabaseOperationException {
    validate();
    this.dao.getDao(clazz).deleteEntity(entity);
  }

  @Override
  public void batchUpdate(List<T> entityList) throws DatabaseOperationException {
    validate();
    this.dao.getDao(clazz).batchUpdate(entityList);
  }

  @Override
  public void batchInsert(List<T> entityList) throws DatabaseOperationException {
    validate();
    this.dao.getDao(clazz).batchInsert(entityList);
  }

  @Override
  public void batchDelete(List<T> entityList) throws DatabaseOperationException {
    validate();
    this.dao.getDao(clazz).batchDelete(entityList);
  }

  public void setClass(Class clazz){
    this.clazz = clazz;
  }

  private void validate() {
    if (clazz == null) {
      throw new IllegalArgumentException("Class of CommonServiceAbstract has to be set!");
    }
  }
}
